﻿using System;
using System.Reflection;
using UnityEngine;
using UnityEngine.Helper;
using UnityEngine.UI;

namespace UnityEditor.UI
{
    [CustomEditor(typeof(DynamicImage))]
    public class DynamicImageEditor : ImageEditor
    { 
        private Sprite lastTexture = null;
        private DynamicImage m_target;
        private DynamicAtlasPreviewGUI _atlasPreview;
        protected override void OnEnable()
        {
            base.OnEnable();
            m_target = (DynamicImage)target;
            _atlasPreview = new DynamicAtlasPreviewGUI(m_target.mainTexture as Texture2D);
            _atlasPreview.OnEnable();
        }
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            GUILayout.Space(5);
            EditorGUILayout.LabelField("DynamicImage");
            GUILayout.Space(5);
            m_target.mGroup = (DynamicAtlasGroup)EditorGUILayout.EnumPopup("Group", m_target.mGroup);

            m_target.spritePath = EditorGUILayout.TextField("spritePath", m_target.spritePath);

            GUILayout.Space(5);


            if (EditorApplication.isPlaying)
            {
                _atlasPreview.OnInspectorGUI(m_target.mGroup);
            }
            else
            {
                if ((lastTexture != m_target.sprite) || (m_target.sprite != null && m_target.spritePath == null))
                {
                    lastTexture = m_target.sprite;
                    string path = PathUtil.RemoveResourcePath(AssetDatabase.GetAssetPath(m_target.sprite));
                    m_target.spritePath = path;
                }

                if (m_target.sprite == null)
                {
                    lastTexture = null;
                    m_target.spritePath = null;
                }
            }
        }
        public override void OnPreviewGUI(Rect rect, GUIStyle background)
        {
            _atlasPreview.OnPreviewGUI(base.OnPreviewGUI,rect,background,m_target.canvasRenderer.GetColor());
        }

    }
}
